package org.cboard.query;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import org.cboard.pojo.KeyValuePair;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("select")
public class SelectDyParamHandler implements DyParamHandler {

    public String getValue(QueryParameter pp, String value) {
        if (value == null || "".equals(value)) {
            JSONObject json = JSONObject.parseObject(pp.getDefaultValue());
            value = json.getString("key");
            if ("string".equals(pp.getDataType())) {
                value = "'" + value + "'";
            }
        } else {
            //相当于全部
            if (QueryConstant.DEFAULT_EMPTY.equals(value)) {
                String content = pp.getContent();
                if ("sql".equals(pp.getDataSource())) {//来源于sql
                    content = pp.getData().toString();
                }
                //[{key:22,value:'22'}{key:22,value:'22'}]
                if (!content.trim().startsWith("[")) {//自动添加[]
                    content = "[" + content + "]";
                }
                List<KeyValuePair> list = JsonParseUtils.parseJson(content, KeyValuePair.class);
                if (!list.isEmpty()) {
                    StringBuilder sb = new StringBuilder();
                    list.forEach(keyValuePair -> {
                        if ("string".equals(pp.getDataType())) {//sting 类型，为每个值加单引号
                            sb.append(",'").append(keyValuePair.getKey()).append("'");
                        } else {
                            sb.append(",").append(keyValuePair.getKey());
                        }
                    });
                    return sb.toString().substring(1);
                }
            } else {//具体的另外一个值
                if ("string".equals(pp.getDataType())) {
                    value = "'" + value + "'";
                }
            }
        }
        return value;

    }

    @Override
    public List<KeyValuePair> getSqlParamValue(String[][] data) {
        if (data == null) {
            return null;
        }
        int col = data[0].length;
        if (col != 2) {//查询不匹配
            throw new RuntimeException("select类型，参数必须为2列");
        }
        List<KeyValuePair> list = Lists.newArrayList();
        int len = data.length;
        for (int i = 1; i < len; i++) {//i=1,因为第一行为表头
            KeyValuePair tt = new KeyValuePair();
            tt.setKey(data[i][0]);
            tt.setValue(data[i][1]);
            list.add(tt);
        }
        return list;
    }

}
